#!/usr/bin/python

""" 
 usage : python sendmail.py
 chmod +x sendmail.py
 chmod 755 /etc/rc.local	If not, /etc/rc.d/rc.local
 vim /etc/rc.local 			If not, /etc/rc.d/rc.local
 insert this : 
 python /home/odroid/sendmail.py &
 or python DOWNLOAD_PATH/sendmail.py &
 before exit 0


	How to set app password : 
	Go to https://account.live.com/proofs/Manage
	App passwords
	Click Create a new app password

"""

# <-- change variables -->
YOUR_SEND_EMAIL 	= '@hotmail.com' # must use @hotmail.com
PASSWORD 			= ''  # hotmail app password 
YOUR_RECEIVE_EMAIL 	= '@' # @gmail.com, @daum.net , @naver.com, etc...

# <-- script -->
import smtplib,requests,signal,sys,time
from email.MIMEText import MIMEText


def search(ip):
	while(1):
		try:# ip querry error
			cnt = requests.get(r'http://jsonip.com').json()['ip']
			if(cnt!=ip):
				# insert sth before sending email
				# don't use os.system()
				ip = cnt
				smtp = smtplib.SMTP('smtp.live.com', 587)
				smtp.ehlo()
				smtp.starttls()
				smtp.login(YOUR_SEND_EMAIL, PASSWORD)
				msg = MIMEText(ip)
				msg['Subject'] = ip
				msg['To'] = YOUR_RECEIVE_EMAIL
				smtp.sendmail(YOUR_SEND_EMAIL, YOUR_RECEIVE_EMAIL, msg.as_string())
				smtp.quit()
				# insert sth after sending email
				# don't use os.system()
		except:pass # add your custom script
		time.sleep(300)	# 5 min sleep

if __name__=='__main__':
	def signal_handler(signal, frame):
		# add your custom handler
		sys.exit(0)
	signal.signal(signal.SIGINT, signal_handler)
	search("")


